<?php
require_once 'MainPageWidget.php';
class CalendarWidget extends MainPageWidget
{
	public $title = 'Календарь';
	public $ui_configurable = false;
	public $ui_frontjs = "widget/calendar.js"; // кнопки в меню настроек виджета

	public $rq_filter_by_day = 'filter_by_day';

	private function makeCalStructure( $input_date_ts ) {

		if (!$input_date_ts) return false;

		$this->ctx->rh->UseClass('RL_CyrDate');
		$input_date = getdate( $input_date_ts );
		// 1. сделать выборку из бд всех дат текущего месяца, когда были записи
		// HACK : 2008-01-31 : lucky
		// для текущего сообщества #294
		$community_oid = $this->getParam('community_oid', $this->acl_assistant->acl_data['comity_oid']);
		$sql = "
			SELECT DISTINCT DAYOFMONTH(obj.ctime) as dt
			FROM store_class_allfeed AS afeed
			INNER JOIN store_objects AS obj ON afeed.oid = obj.oid
			WHERE obj.ctime BETWEEN CONCAT(
				YEAR(FROM_UNIXTIME(".$input_date_ts.")),
				'-',
				MONTH(FROM_UNIXTIME(".$input_date_ts.")),
				'-',
				'01'						)
			AND LAST_DAY(FROM_UNIXTIME(".$input_date_ts."))
			AND afeed.community_oid = $community_oid
		";

		$ors = $this->store->query($sql);

		while ($row = $ors->next()) {
			$activity_days[ $row['dt'] ] = 1;
			unset($row);
		}

		// 2. собрать структуру для шаблонного движка
		// рассчитаем метку Юникс на начало первой недели месяца, который выводим
		$start_ts = RL_CyrDate::newFromTimestamp( $input_date_ts )->monthStart()->weekStart()->unix_mark();

		// рассчитаем метку Юникс на конец последней недели месяца
		$end_ts = RL_CyrDate::newFromTimestamp( $input_date_ts )->monthEnd()->weekEnd()->unix_mark();

		for($_ts=$start_ts; $_ts<=$end_ts; $_ts = $_ts + 24*3600) {

			$week_num = idate( "W", $_ts );
			$day_info = getdate( $_ts );
			$wd_num = $day_info['wday']; // порядковый номер дня недели

			if ($wd_num==0) { // воскресенье
				$wd_num = 6;
			} else { $wd_num--; }

			$day_struct['day'] = $day_info['mday'];
			if (isset($activity_days[ $day_info['mday'] ])) {
				$day_struct['act_day'] = $day_info['mday'] > 9 ? $day_info['mday'] : "0".$day_info['mday'];
				$day_struct['act_month'] = $day_info['mon'] > 9 ? $day_info['mon'] : "0".$day_info['mon'];
				$day_struct['act_year'] = $day_info['year'];

				$day_struct['url'] = $this->hrefFilterFeedByDay(
					$day_struct['act_year']."-".$day_struct['act_month']."-".$day_struct['act_day']
				);
			}
			if ($input_date['mon'] != $day_info['mon']) $day_struct['not_current_month'] = 1;

			$month[ $week_num ][ $wd_num ] = $day_struct;
			unset($day_struct);
		}
		return $month;
	}

	public function hrefFilterFeedByDay ($day)
	{

		$rule = isset($this->params['tdi_url']) ? 'showfeed_tdi' : 'showfeed';

		$GET = array();
		if ($day) $GET[$this->rq_filter_by_day] = $day;

		$ug = new RL_URLGenerator($this->parent->rh->router->getRule($rule));
		$ug->setRouter($this->parent->rh->router);
		$ug->setParam('community_url', $this->acl_assistant->acl_data['community_url']);
		$ug->setGet($GET);

		$url = $ug->generateUrl();
		return $url;
	} // end of method hrefShowFeed

	private function makeContainerStructure( $input_date_ts ) {

		if (!$input_date_ts) return false;
		$this->ctx->rh->UseClass('RL_CyrDate');

		$rl_cd = RL_CyrDate::newFromTimestamp($input_date_ts);

		$content['month']['title'] = mb_convert_case($rl_cd->format("%N"), MB_CASE_TITLE, "UTF-8");
		$content['month']['year'] = $rl_cd->year();

		$rl_cd_p = RL_CyrDate::newFromTimestamp($rl_cd->mktime(0,0,0,-1));
		$content['pmonth']['title'] = mb_convert_case($rl_cd_p->format("%N"), MB_CASE_TITLE, "UTF-8");
		$content['pmonth']['ts'] = $rl_cd_p->unix_mark();
		$content['pmonth']['year'] = $rl_cd_p->year();

		$rl_cd_n = RL_CyrDate::newFromTimestamp($rl_cd->mktime(0,0,0,1));
		$content['nmonth']['title'] = mb_convert_case($rl_cd_n->format("%N"), MB_CASE_TITLE, "UTF-8");
		$content['nmonth']['ts'] = $rl_cd_n->unix_mark();
		$content['nmonth']['year'] = $rl_cd_n->year();


		return $content;
	}

	public function ajax_Cal( $input_date_ts ) {

		$content = $this->makeContainerStructure( $input_date_ts );

		$this->content = $content;
		$this->content['month']['cal'] = $this->makeCalStructure( $input_date_ts );

		$view = $this->ctx->rh->views->findByName('WG_CalendarWidget:cal');
		$view->data['widget'] = $this;
		$content['month']['calhtml'] = $view->getContent();

		return $content;

	}

	public function Render() {

		$input_date_ts = mktime();
		$content = $this->makeContainerStructure( $input_date_ts );

		$content['month']['cal'] = $this->makeCalStructure( $input_date_ts );

		$this->content = $content;
		return $this;
	}

}

